package initialize

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"konglu-pay/global"
)

func Viper() {
	v := viper.New()
	v.SetConfigFile("application.yaml")
	unmarshalProfiles(v)
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Printf("config changed: %v", e.Name)
		unmarshalProfiles(v)
	})
	fmt.Println("loaded related config ok")
}

func unmarshalProfiles(v *viper.Viper) {
	if err := v.ReadInConfig(); err != nil {
		_ = fmt.Errorf("config read error: %v", err)
	}
	unmarshalConfig(v, global.Setting, "app")
}

func unmarshalConfig(v *viper.Viper, config any, alias string) {
	if err := v.Unmarshal(config); err != nil {
		_ = fmt.Errorf("[%s] config load error: %v", alias, err)
	}
}
